﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using System.Configuration;
using Newtonsoft.Json;
using DevExpress.XtraEditors.DXErrorProvider;

namespace MachineBuildingSystem
{
    public partial class OrderAddUC : UserControl
    {
        private string m_CurrentUser = "";
        private string m_Password = "";
        private List<long> m_ActionList = new List<long>();

        private OrderTypeEnum m_Type = OrderTypeEnum.OrderDetail;
        private DataTable m_BindDT = null;
        
        //基础数据信息
        private BaseDataInfo m_BaseDataInfo = null;
        //选择的客户Id
        private long m_SelectedCustomerId = -1;
        //选择的物料ID
        private long m_SelectedmaterialId = -1;
        //选择的生产线
        private long m_SelectedWorkingId = -1;
        //当前order
        private OrderInfo m_OrderInfo = null;
        //区域
        private List<ZoneInfo> m_ZoneInfoList = new List<ZoneInfo>();
        //实施配比主表
        private DataTable m_MainDT = null;
        //实施配比子表
        private DataTable m_SubDT = null;

        private DataSet m_BinDataSet = null;
        //物料对照，key为code,value为机楼物料名称
        //private Dictionary<string, string> m_MaterialCrossDic = new Dictionary<string, string>();
        //物料名称与物料类型对照
        private Dictionary<string, string> m_MaterialNameAndTypeDic = new Dictionary<string, string>();
        public OrderAddUC()
        {
            InitializeComponent();
        }

        private void OrderAddUC_Load(object sender, EventArgs e)
        {   
            ContextMenu emptyMenu = new ContextMenu();
            mruEditFactoryName.Properties.ContextMenu = emptyMenu;
            mruEditCustomer.Properties.ContextMenu = emptyMenu;
            mruEditProjectName.Properties.ContextMenu = emptyMenu;
            mruEditConstructionSite.Properties.ContextMenu = emptyMenu;
            dateEditPlaProTime.Properties.ContextMenu = emptyMenu;
            mruEditWorking.Properties.ContextMenu = emptyMenu;
            mruEditFormulaCode.Properties.ContextMenu = emptyMenu;
            mruEditStrengthGrade.Properties.ContextMenu = emptyMenu;
            mruEditSlump.Properties.ContextMenu = emptyMenu;
            txtOtherRequire.Properties.ContextMenu = emptyMenu;
            mruEditTransport.Properties.ContextMenu = emptyMenu;
            txtClientPhone.Properties.ContextMenu = emptyMenu;
            mruEditZone.Properties.ContextMenu = emptyMenu;
            txtZonePrice.Properties.ContextMenu = emptyMenu;
            spinEditNumber.Properties.ContextMenu = emptyMenu;
            txtProductPrice.Properties.ContextMenu = emptyMenu;
            txtUnitPrice.Properties.ContextMenu = emptyMenu;
            txtConcreteLoan.Properties.ContextMenu = emptyMenu;
            txtBasicPath.Properties.ContextMenu = emptyMenu;
            txtBasicPrice.Properties.ContextMenu = emptyMenu;
            txtOverPrice.Properties.ContextMenu = emptyMenu;
            spinEditActualDistance.Properties.ContextMenu = emptyMenu;
            txtOverDistance.Properties.ContextMenu = emptyMenu;
            txtEachUnitPrice.Properties.ContextMenu = emptyMenu;
            txtBasicFreight.Properties.ContextMenu = emptyMenu;
            txtOrderTotalAmount.Properties.ContextMenu = emptyMenu;
            txtCustomerSaleCount.Properties.ContextMenu = emptyMenu;
        }

        #region 初始化
        private void InitMainDT()
        {
            m_MainDT = new DataTable();
            m_MainDT.Columns.Add("id");
            m_MainDT.Columns.Add("labels");
            m_MainDT.Columns.Add("formulaDate", typeof(DateTime));
            m_MainDT.Columns.Add("executeStatus");
            m_MainDT.Columns.Add("executeDate", typeof(DateTime));
            m_MainDT.Columns.Add("otherCode");
        }

        private void InitSubDT()
        {
            m_SubDT = new DataTable();
            m_SubDT.Columns.Add(CommonHelper.CreateDataColumn("mainId", "mainId"));
            m_SubDT.Columns.Add(CommonHelper.CreateDataColumn("id", "id"));
            m_SubDT.Columns.Add(CommonHelper.CreateDataColumn("code", "物料编码"));
            m_SubDT.Columns.Add(CommonHelper.CreateDataColumn("name", "物料名称"));
            m_SubDT.Columns.Add(CommonHelper.CreateDataColumn("sstd", "规格型号"));
            m_SubDT.Columns.Add(CommonHelper.CreateDataColumn("quantity", "用量"));
            m_SubDT.Columns.Add(CommonHelper.CreateDataColumn("controlStoreName", "仓位"));
        }
        #endregion

        #region 公共方法
        public void RefreshOrder(string user, string password, List<long> actionList, OrderTypeEnum type, BaseDataInfo info, OrderInfo order)
        {
            InitMainDT();
            InitSubDT();
            //InitValidationRules();
            m_BinDataSet = new DataSet();
            m_BinDataSet.Tables.Add(m_MainDT);
            m_BinDataSet.Tables.Add(m_SubDT);
            DataRelation relation = new DataRelation("配方信息", m_BinDataSet.Tables[0].Columns["id"], m_BinDataSet.Tables[1].Columns["mainId"]);
            m_BinDataSet.Relations.Add(relation);

            m_CurrentUser = user;
            m_Password = password;
            m_ActionList = actionList;
            m_Type = type;
            m_OrderInfo = order;
            if (order != null)
            {
                m_SelectedWorkingId = order.workingId;
                m_SelectedCustomerId = order.customerId;
                m_SelectedmaterialId = order.materialId;
            }
            else
                m_SelectedWorkingId = -1;

            m_BaseDataInfo = info;
            CleanForm();

            //订单新增和修改
            if (type == OrderTypeEnum.OrderAdd || type == OrderTypeEnum.OrderUpdate || type == OrderTypeEnum.OrderUpdateByAudited)
            {
                SetFormStatus(true);
                if (type == OrderTypeEnum.OrderUpdate)
                {
                    mruEditCustomer.Properties.ReadOnly = true;
                    //mruEditStrengthGrade.Properties.ReadOnly = true;
                    mruEditZone.Properties.ReadOnly = true;
                    spinEditNumber.Properties.ReadOnly = true;
                    //加载订单信息
                    FillOrderInfo(order);
                }
                if (type == OrderTypeEnum.OrderUpdateByAudited)
                {
                    mruEditCustomer.Properties.ReadOnly = true;
                    //dateEditPlaProTime.Properties.ReadOnly = true;
                    mruEditProjectName.Properties.ReadOnly = true;
                    mruEditConstructionSite.Properties.ReadOnly = true;
                    mruEditWorking.Properties.ReadOnly = true;
                    mruEditStrengthGrade.Properties.ReadOnly = true;
                    mruEditSlump.Properties.ReadOnly = true;
                    txtOtherRequire.Properties.ReadOnly = true;
                    mruEditTransport.Properties.ReadOnly = true;
                    txtClientPhone.Properties.ReadOnly = true;
                    mruEditZone.Properties.ReadOnly = true;
                    spinEditNumber.Properties.ReadOnly = true;
                    //spinEditActualDistance.Properties.ReadOnly = true;
                    //加载订单信息
                    FillOrderInfo(order);
                }
                else if (type == OrderTypeEnum.OrderAdd)
                {
                    //订单新增默认计划生产时间
                    dateEditPlaProTime.EditValue = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss"));
                    //厂名
                    mruEditFactoryName.Text = ConfigurationManager.AppSettings["BelongCorpName"].ToString();
                    //默认配方代码，不可选
                    mruEditFormulaCode.Text = ConfigurationManager.AppSettings["DefaultMaterial"].ToString();
                    m_SelectedmaterialId = long.Parse(ConfigurationManager.AppSettings["DefaultMaterialId"].ToString());
                }
                InitCmbData(info);
            }
            else if (type == OrderTypeEnum.OrderDetail)//订单详情
            {
                SetFormStatus(false);
                //加载订单信息
                FillOrderInfo(order);
                //加载该订单下的实施配比

                BackgroundWorker backgroundWorker = new BackgroundWorker();
                backgroundWorker.DoWork += backgroundWorker_DoWork;
                backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
                backgroundWorker.RunWorkerAsync(order.id);
            }
        }
        #endregion

        #region 线程
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            long orderId = long.Parse(e.Argument.ToString());
            List<SaleFormulasData> saleFormulasDataList = null;
            try
            {
                saleFormulasDataList = DataHelper.GetSaleFormulas(m_CurrentUser, m_Password, orderId);
                if (saleFormulasDataList != null && saleFormulasDataList.Count >= 0)
                {
                    foreach (SaleFormulasData data in saleFormulasDataList)
                    {
                        List<SaConcreteFormulaData> subList = DataHelper.GetSaConcreteFormulaLines(m_CurrentUser, m_Password, data.id);
                        if (subList != null)
                            data.SaConcreteFormulaDataList = subList;
                    }
                }
            }
            catch
            {
                throw;
            }
            e.Result = saleFormulasDataList;
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
                return;
            if (e.Error != null)
            {
                LogHelper.error("加载实施配方数据异常：" + e.Error.Message);
                return;
            }
            List<SaleFormulasData> saleFormulasDataList = e.Result as List<SaleFormulasData>;

            m_SubDT.Clear();
            m_MainDT.Clear();
            gdcBalance.DataSource = m_MainDT;
            if (saleFormulasDataList == null || saleFormulasDataList.Count == 0)
                return;
            //按发货时间降序排序
            List<SaleFormulasData> tempList = 
                saleFormulasDataList.OrderByDescending(temp => temp.formulaDate).ToList<SaleFormulasData>();

            foreach (SaleFormulasData data in tempList)
            {
                m_MainDT.Rows.Add(data.id, data.labels, data.formulaDate, data.executeStatus, data.executeDate, data.otherCode);
                if (data.SaConcreteFormulaDataList == null || data.SaConcreteFormulaDataList.Count == 0)
                    continue;
                foreach (SaConcreteFormulaData item in data.SaConcreteFormulaDataList)
                {
                    m_SubDT.Rows.Add(data.id, item.id, item.materialCode, item.materialName, item.materialSstd, item.quantity, item.controlStoreName);
                }
            }
            gdcBalance.DataSource = m_BinDataSet.Tables[0];
        }
        #endregion

        #region 私有方法
        //初始化下拉框数据
        private void InitCmbData(BaseDataInfo info)
        {
            try
            {
                //初始化客户
                InitMruEditCustomer(info.CustomerInfoList);
                //初始化工程名称,实时变化
                InitMruEditProjectName(GetProjectData());
                //施工部位
                InitMruEditConstructionSite(GetConstructSiteData());
                //坍落度要求
                InitMruEditSlump(info.SlumpInfoInfoList);
                //强度等级下拉框
                InitMruEditStrengthGrade();
                //施工地址下拉框
                InitMruEditConstructionAddr();
                //区域
                InitMruEditZone(GetZoneData());
                //初始化输送方式
                InitMruEditTransport(info.TransportInfoList);
                //初始化生产线下拉框
                InitMruEditProductLine();
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化下拉框异常：" + ex.Message);
                return;
            }
        }

        //工程名称
        private List<ProjectInfo> GetProjectData()
        {
            List<ProjectInfo> projectInfoList = null;
            try
            {
                projectInfoList = DataHelper.GetProjectInfo(m_CurrentUser, m_Password, "null");
            }
            catch
            {
                throw;
            }
            return projectInfoList;
        }

        //施工部位
        private List<ConstructSiteInfo> GetConstructSiteData()
        {
            List<ConstructSiteInfo> list = null;
            try
            {
                list = DataHelper.GetConstructSiteInfo(m_CurrentUser, m_Password);
            }
            catch
            {
                throw;
            }
            return list;
        }

        //区域信息
        private List<ZoneInfo> GetZoneData()
        {
            List<ZoneInfo> list = null;
            try
            {
                int belongcorpId = int.Parse(ConfigurationManager.AppSettings["BelongCorpId"]);
                list = DataHelper.GetZoneInfo(m_CurrentUser, m_Password, belongcorpId);
            }
            catch
            {
                throw;
            }
            return list;
        }

        //界面填充订单信息
        private void FillOrderInfo(OrderInfo order)
        {
            mruEditFactoryName.Text = order.corpName;
            mruEditCustomer.SelectedItem = CommonHelper.FindDataInfoByKey(mruEditCustomer, order.customerId);
            if (mruEditCustomer.SelectedItem == null || mruEditCustomer.SelectedItem == "")
            {
                m_SelectedCustomerId = order.customerId;
                mruEditCustomer.Text = order.customerName;
            }
            dateEditPlaProTime.Text = order.productDate.ToString("yyyy-MM-dd");
            mruEditProjectName.Text = order.projectName;
            mruEditConstructionSite.Text = order.constructSite;
            mruEditWorking.Text = order.workingCenterName;
            mruEditFormulaCode.Text = order.materialCode; ;
            mruEditStrengthGrade.Text = order.strengthGrade;
            mruEditSlump.Text = order.slump;
            txtOtherRequire.Text = order.otherRequirement;
            mruEditTransport.Text = order.transport;
            txtClientPhone.Text = order.phone;
            mruEditZone.Text = order.areaName;
            txtZonePrice.Text = order.areaPrice.ToString();
            txtProductPrice.Text = order.productPrice.ToString();
            //单价 = 产品价格 + 区域调价
            txtUnitPrice.Text = (order.productPrice + order.areaPrice).ToString();
            //基本计价路程
            txtBasicPath.Text = order.basicPath.ToString();
            //基本运价
            txtBasicPrice.Text = order.basicPrice.ToString();
            //超公里运价
            txtOverPrice.Text = order.superPrice.ToString() ;
            spinEditNumber.Text = order.orderQuantity.ToString();
            //实际距离
            spinEditActualDistance.EditValue = order.actualRange;
            //实施地址
            mruEditConstructionAddr.Text = order.constructionAddr;
        }

        //界面状态
        private void SetFormStatus(bool isAdd)
        {
            mruEditCustomer.Properties.ReadOnly = !isAdd;
            dateEditPlaProTime.Properties.ReadOnly = !isAdd;
            mruEditProjectName.Properties.ReadOnly = !isAdd;
            mruEditConstructionSite.Properties.ReadOnly = !isAdd;
            mruEditConstructionAddr.Properties.ReadOnly = !isAdd;
            mruEditWorking.Properties.ReadOnly = !isAdd;
            mruEditStrengthGrade.Properties.ReadOnly = !isAdd;
            mruEditSlump.Properties.ReadOnly = !isAdd;
            txtOtherRequire.Properties.ReadOnly = !isAdd;
            mruEditTransport.Properties.ReadOnly = !isAdd;
            txtClientPhone.Properties.ReadOnly = !isAdd;
            mruEditZone.Properties.ReadOnly = !isAdd;
            spinEditNumber.Properties.ReadOnly = !isAdd;
            spinEditActualDistance.Properties.ReadOnly = !isAdd;
            if (isAdd)
            {
                lcgOrderDetail.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                lcgFormula.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            }
            else
            {
                lcgOrderDetail.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                lcgFormula.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            }
            emptySpaceStatus(isAdd);
        }

        private void emptySpaceStatus(bool isAdd)
        {
            emptySpaceItem1.Visibility = isAdd == true ? DevExpress.XtraLayout.Utils.LayoutVisibility.Always
                : DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            emptySpaceItem2.Visibility = isAdd == true ? DevExpress.XtraLayout.Utils.LayoutVisibility.Always
               : DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            emptySpaceItem3.Visibility = isAdd == true ? DevExpress.XtraLayout.Utils.LayoutVisibility.Always
               : DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            emptySpaceItem4.Visibility = isAdd == true ? DevExpress.XtraLayout.Utils.LayoutVisibility.Always
               : DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            emptySpaceItem5.Visibility = isAdd == true ? DevExpress.XtraLayout.Utils.LayoutVisibility.Always
               : DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            emptySpaceItem6.Visibility = isAdd == true ? DevExpress.XtraLayout.Utils.LayoutVisibility.Always
                : DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            emptySpaceItem7.Visibility = isAdd == true ? DevExpress.XtraLayout.Utils.LayoutVisibility.Always
               : DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            emptySpaceItem8.Visibility = isAdd == true ? DevExpress.XtraLayout.Utils.LayoutVisibility.Always
                : DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            emptySpaceItem9.Visibility = isAdd == true ? DevExpress.XtraLayout.Utils.LayoutVisibility.Always
               : DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            emptySpaceItem10.Visibility = isAdd == true ? DevExpress.XtraLayout.Utils.LayoutVisibility.Always
                : DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            emptySpaceItem11.Visibility = isAdd == true ? DevExpress.XtraLayout.Utils.LayoutVisibility.Always
                : DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            emptySpaceItem12.Visibility = isAdd == true ? DevExpress.XtraLayout.Utils.LayoutVisibility.Always
                : DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            emptySpaceItem13.Visibility = isAdd == true ? DevExpress.XtraLayout.Utils.LayoutVisibility.Always
                : DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            emptySpaceItem14.Visibility = isAdd == true ? DevExpress.XtraLayout.Utils.LayoutVisibility.Always
                : DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
        }

        //初始化客户下拉框
        private void InitMruEditCustomer(List<CustomerInfo> customerList)
        {
            try
            {
                if (customerList == null || customerList.Count == 0)
                    return;
                mruEditCustomer.Properties.Items.Clear();
                foreach (CustomerInfo customer in customerList)
                {
                    DataInfo data = new DataInfo();
                    data.Id = customer.customerId;
                    data.Value = customer.customerName  + " " + customer.customerCode;
                    mruEditCustomer.Properties.Items.Add(data);
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化客户下拉框数据异常：" + ex.Message);
            }
        }

        //初始化工程名称下拉框
        private void InitMruEditProjectName(List<ProjectInfo> projectInfoList)
        {
            try
            {
                if (projectInfoList == null || projectInfoList.Count == 0)
                    return;
                mruEditProjectName.Properties.Items.Clear();
                foreach (ProjectInfo project in projectInfoList)
                    mruEditProjectName.Properties.Items.Add(project.name);
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化工程名称下拉框异常：" + ex.Message);
            }
        }

        //初始化坍落度下拉框
        private void InitMruEditSlump(List<SlumpInfo> slumpInfoList)
        {
            try
            {
                if (slumpInfoList == null || slumpInfoList.Count == 0)
                    return;
                mruEditSlump.Properties.Items.Clear();
                foreach (SlumpInfo slump in slumpInfoList)
                {
                    DataInfo data = new DataInfo();
                    data.Id = slump.id;
                    data.Value = slump.name;
                    mruEditSlump.Properties.Items.Add(data);
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化坍落度下拉框异常：" + ex.Message);
            }
        }

        //初始化强度等级下拉框
        private void InitMruEditStrengthGrade()
        {
            try
            {
                string strengthGrade = ConfigurationManager.AppSettings["StrengthGrade"];
                string[] strengthGradeArr = strengthGrade.Split(',');
                if (strengthGradeArr == null || strengthGradeArr.Length == 0)
                    return;
                mruEditStrengthGrade.Properties.Items.Clear();
                foreach (string grade in strengthGradeArr)
                {
                    mruEditStrengthGrade.Properties.Items.Add(grade);
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化强度等级下拉框异常：" + ex.Message);
            }
        }

        //初始化施工地址下拉框
        private string m_HaveConstructionAddrStr = "";
        private void InitMruEditConstructionAddr()
        {
            try
            {
                mruEditConstructionAddr.Properties.Items.Clear();
                m_HaveConstructionAddrStr = ConfigurationManager.AppSettings["ConstructionAddrStr"];
                string[] constructionAddrArr = m_HaveConstructionAddrStr.Split(',');
                if (constructionAddrArr == null || constructionAddrArr.Length == 0)
                    return;
                foreach (string constructionAddr in constructionAddrArr)
                {
                    mruEditConstructionAddr.Properties.Items.Add(constructionAddr);
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化施工地址下拉框异常：" + ex.Message);
            }
        }

        //初始化区域下拉框
        private void InitMruEditZone(List<ZoneInfo> zoneInfoList)
        {
            try
            {
                m_ZoneInfoList = zoneInfoList;
                if (zoneInfoList == null || zoneInfoList.Count == 0)
                    return;
                mruEditZone.Properties.Items.Clear();
                foreach (ZoneInfo zone in zoneInfoList)
                {
                    DataInfo data = new DataInfo ();
                    data.Id = zone.id;
                    data.Value = zone.names;
                    mruEditZone.Properties.Items.Add(data);
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化区域下拉框异常：" + ex.Message);
            }
        }

        //初始化施工部位下拉框
        private void InitMruEditConstructionSite(List<ConstructSiteInfo> constructSiteInfoList)
        {
            try
            {
                if (constructSiteInfoList == null || constructSiteInfoList.Count == 0)
                    return;
                mruEditConstructionSite.Properties.Items.Clear();
                foreach (ConstructSiteInfo constructSite in constructSiteInfoList)
                    mruEditConstructionSite.Properties.Items.Add(constructSite.names);
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化施工部位下拉框异常：" + ex.Message);
            }
        }

        //初始化输送方式下拉框
        private void InitMruEditTransport(List<TransportInfo> transportInfoList)
        {
            try
            {
                if (transportInfoList == null || transportInfoList.Count == 0)
                    return;
                mruEditTransport.Properties.Items.Clear();
                foreach (TransportInfo constructSite in transportInfoList)
                {
                    DataInfo info = new DataInfo();
                    info.Id = constructSite.id;
                    info.Value = constructSite.names;
                    mruEditTransport.Properties.Items.Add(info);
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化输送方式下拉框异常：" + ex.Message);
            }
        }

        //初始化生产线下拉框
        private void InitMruEditProductLine()
        {
            try
            {
                string str = ConfigurationManager.AppSettings["ProductLines"].ToString();
                string[] productLineArr = str.Split(',');
                if (productLineArr.Length == 0)
                    return;
                mruEditWorking.Properties.Items.Clear();
                foreach (string productLine in productLineArr)
                {
                    string[] strArr = productLine.Split('/');
                    DataInfo data = new DataInfo();
                    data.Id = Convert.ToInt64(strArr[0]);
                    data.Value = strArr[1];
                    mruEditWorking.Properties.Items.Add(data);
                }
                mruEditWorking.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化生产线下拉框数据异常：" + ex.Message);
            }
        }
        #endregion

        #region 界面按钮事件
        public delegate void OrderAddSuccessEventHandler(object sender, EventArgs e);
        public event OrderAddSuccessEventHandler OrderAddSuccessEvent;
        //发送订单
        private void btnSendOrder_Click(object sender, EventArgs e)
        {
            if (!ValidateOrderAdd())
                return;
            OrderInfo order = GetOrderInfo();
            if (order == null)
            {
                MessageBox.Show(this, "获取销售订单信息为null,详细信息请参考日志文件");
                return;
            }
            string tempJsonData = "";
            try
            {
                List<Dictionary<string, object>> list = GetOrderSaveData(order);
                if (m_Type == OrderTypeEnum.OrderUpdate || m_Type == OrderTypeEnum.OrderUpdateByAudited)
                {
                    Dictionary<string, object> dic = list[0];
                    dic.Add("id", m_OrderInfo.id);
                    dic.Add("mainId", m_OrderInfo.mainId);
                }
                //保存销售订单
                CGlobal.strSwapJsonData = JsonConvert.SerializeObject(list);
                tempJsonData = CGlobal.strSwapJsonData;
                bool isSuccess = DataHelper.SaveSaleOrder(m_CurrentUser, m_Password);
                if (isSuccess)
                {
                    MessageBox.Show(this, "保存成功");
                    //记忆施工地址
                    if (!string.IsNullOrEmpty(order.constructionAddr) && 
                        !m_HaveConstructionAddrStr.Split(',').Contains(order.constructionAddr))
                    {
                        m_HaveConstructionAddrStr += "," + order.constructionAddr;
                        Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                        cfa.AppSettings.Settings["ConstructionAddrStr"].Value = m_HaveConstructionAddrStr;
                        cfa.Save();
                        ConfigurationManager.RefreshSection("appSettings");
                    }
                    //保存成功后关闭该窗口，并刷新订单列表
                    if (OrderAddSuccessEvent != null)
                    {
                        OrderAddSuccessEvent(this, e);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("保存销售订单信息异常：" + ex.ToString() + ",Json数据：" + tempJsonData);
                MessageBox.Show(this, "保存失败:" + ex.Message);
            }
        }

        private bool ValidateOrderAdd()
        {
            if (string.IsNullOrEmpty(mruEditFactoryName.Text.Trim()))
            {
                MessageBox.Show("厂名不能为空!");
                mruEditFactoryName.Focus();
                return false;
            }
            //if (string.IsNullOrEmpty(mruEditCustomer.Text.Trim()))
            //{
            //    MessageBox.Show("客户不能为空!");
            //    mruEditCustomer.Focus();
            //    return false;
            //}
            if (m_SelectedCustomerId <= 0)
            {
                MessageBox.Show("客户不能为空,请选择!");
                mruEditCustomer.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(mruEditProjectName.Text.Trim()))
            {
                MessageBox.Show("工程名称不能为空!");
                mruEditProjectName.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(mruEditConstructionSite.Text.Trim()))
            {
                MessageBox.Show("施工部位不能为空!");
                mruEditConstructionSite.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(mruEditStrengthGrade.Text.Trim()))
            {
                MessageBox.Show("强度等级不能为空!");
                mruEditStrengthGrade.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(mruEditTransport.Text.Trim()))
            {
                MessageBox.Show("输送方式不能为空!");
                mruEditTransport.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(mruEditFormulaCode.Text.Trim()))
            {
                MessageBox.Show("配方代码不能为空!");
                mruEditFormulaCode.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(mruEditZone.Text.Trim()))
            {
                MessageBox.Show("区域不能为空!");
                mruEditZone.Focus();
                return false;
            }
            if (Convert.ToDecimal(this.spinEditNumber.EditValue) == 0)
            {
                MessageBox.Show("订单数量不能为0!");
                spinEditNumber.Focus();
                return false;
            }
            return true;
        }

        //从界面获取数据
        private OrderInfo GetOrderInfo()
        {
            OrderInfo order = new OrderInfo();
            try
            {
                CustomerInfo customer = GetCustomerById(m_SelectedCustomerId);
                if (customer != null)
                {
                    order.customerId = customer.customerId;
                    order.customerCode = customer.customerCode;
                    order.customerName = customer.customerName;
                }
                order.productDate = Convert.ToDateTime(dateEditPlaProTime.EditValue);
                order.projectName = mruEditProjectName.Text.Trim();
                order.constructSite = this.mruEditConstructionSite.Text.Trim();
                //生产线
                order.workingId = m_SelectedWorkingId;
                order.workingCenterName = mruEditWorking.Text.Trim();
                //配方代码默认
                order.corpId = long.Parse(ConfigurationManager.AppSettings["BelongCorpId"].ToString());
                order.corpName = mruEditFactoryName.Text.Trim();
                if (m_Type == OrderTypeEnum.OrderAdd)
                {
                    order.materialId = long.Parse(ConfigurationManager.AppSettings["DefaultMaterialId"].ToString());
                    order.materialCode = ConfigurationManager.AppSettings["DefaultMaterialCode"].ToString();
                    order.materialName = ConfigurationManager.AppSettings["DefaultMaterial"].ToString();
                }
                else if (m_Type == OrderTypeEnum.OrderUpdate || m_Type == OrderTypeEnum.OrderUpdateByAudited )
                {
                    if (m_OrderInfo.materialId == long.Parse(ConfigurationManager.AppSettings["DefaultMaterialId"].ToString()))
                    {
                        order.materialId = long.Parse(ConfigurationManager.AppSettings["DefaultMaterialId"].ToString());
                        order.materialCode = ConfigurationManager.AppSettings["DefaultMaterialCode"].ToString();
                        order.materialName = ConfigurationManager.AppSettings["DefaultMaterial"].ToString();
                    }
                    else
                    {
                        order.materialId = m_OrderInfo.materialId;
                        order.materialCode = m_OrderInfo.orderCode;
                        order.materialName = m_OrderInfo.materialName;
                    }
                    order.executeStatus = m_OrderInfo.executeStatus;
                    order.version = m_OrderInfo.version;
                }
                order.strengthGrade = mruEditStrengthGrade.Text.Trim();
                order.slump = mruEditSlump.Text.Trim();
                order.otherRequirement = txtOtherRequire.Text.Trim();
                order.transport = mruEditTransport.Text.Trim();
                //根据传输方式获取类型
                var query = from temp in m_BaseDataInfo.TransportInfoList
                            where temp.names == order.transport
                            select temp;
                if(query.Count() >= 1)
                    order.types = query.ToList<TransportInfo>()[0].types;
                order.phone = txtClientPhone.Text.Trim();
                order.areaName = mruEditZone.Text.Trim();
                order.orderQuantity = spinEditNumber.Value;

                order.areaPrice = Convert.ToDecimal(this.txtZonePrice.Text.Trim());
                order.unitPrice = Convert.ToDecimal(this.txtUnitPrice.Text.Trim());
                order.basicPath = Convert.ToDecimal(this.txtBasicPath.Text.Trim());
                order.basicPrice = Convert.ToDecimal(this.txtBasicPrice.Text.Trim());
                order.superPrice = Convert.ToDecimal(this.txtOverPrice.Text.Trim());
                order.actualRange = this.spinEditActualDistance.Value;
                //施工地址
                order.constructionAddr = this.mruEditConstructionAddr.Text.Trim();
            }
            catch (Exception ex)
            {
                LogHelper.error("从界面获取订单信息异常：" + ex.ToString());
                return null;
            }
            return order;
        }

        //保存订单时获取key Value 的信息
        private List<Dictionary<string, object>> GetOrderSaveData(OrderInfo order)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            Dictionary<string, object> dic = new Dictionary<string, object>();
            //装车类型，默认散装
            dic.Add("type", 0);
            dic.Add("belongCorpId", order.corpId);
            dic.Add("customerId", order.customerId);
            dic.Add("productDate", order.productDate.ToString("yyyy-MM-dd HH:mm:ss"));
            dic.Add("projectName", order.projectName);
            dic.Add("constructSite", order.constructSite);
            dic.Add("workingId", order.workingId);
            dic.Add("materialId", order.materialId);
            dic.Add("strengthGrade", order.strengthGrade);
            dic.Add("slump", order.slump);
            dic.Add("otherRequirement", order.otherRequirement);
            dic.Add("transport", order.transport);
            dic.Add("types", order.types);
            //委托人电话
            dic.Add("phone", order.phone);
            dic.Add("areaName", order.areaName);
            dic.Add("mainQuantity", order.orderQuantity);
            //商标Id默认3，
            dic.Add("trademarkId", 3);
            //包装方式，散装无，袋装有
            dic.Add("packTypeId", 0);
            dic.Add("actualRange", order.actualRange);
            dic.Add("areaPrice", order.areaPrice);
            //存入的单价为产品价格
            dic.Add("unitPrice", order.productPrice);
            dic.Add("basicPath", order.basicPath);
            dic.Add("basicPrice", order.basicPrice);
            dic.Add("superPrice", order.superPrice);
            dic.Add("executeStatus", order.executeStatus);
            dic.Add("version", order.version);
            //施工地址
            dic.Add("freeField15", order.constructionAddr);

            list.Add(dic);
            return list;
        }

        //根据客户Id获取客户信息
        private CustomerInfo GetCustomerById(long customerId)
        {
            CustomerInfo customerInfo = new CustomerInfo();
            try
            {
                var query = from temp in m_BaseDataInfo.CustomerInfoList
                            where temp.customerId == customerId
                            select temp;
                if (query == null)
                    return null;
                foreach (var item in query)
                {
                    customerInfo = item;
                    break;
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("根据客户ID：" + customerId + "获取客户信息异常：" + ex.ToString());
                return null;
            }
            return customerInfo;
        }

        //取消
        private void btnCancel_Click(object sender, EventArgs e)
        {
            //取消验证
            if (myReturnEvent != null)
                myReturnEvent(null, null);
        }

        //清空界面信息
        private void CleanForm()
        {
            mruEditFactoryName.Text = "";
            mruEditCustomer.Text = "";
            dateEditPlaProTime.EditValue = DateTime.Now.AddDays(1);
            mruEditProjectName.Text = "";
            mruEditConstructionSite.Text = "";
            mruEditFormulaCode.Text = "";
            mruEditWorking.Text = "";
            mruEditStrengthGrade.Text = "";
            mruEditSlump.Text = "";
            txtOtherRequire.Text = "";
            mruEditTransport.Text = "";
            txtClientPhone.Text = "";
            mruEditZone.Text = "";
            txtZonePrice.Text = "0";
            spinEditNumber.Value = 0;
            txtProductPrice.Text = "0";
            txtUnitPrice.Text = "0";
            txtConcreteLoan.Text = "0";
            txtBasicPath.Text = "0";
            txtBasicPrice.Text = "0";
            txtOverPrice.Text = "0";
            spinEditActualDistance.Value = 0;
            txtOverDistance.Text = "0";
            txtEachUnitPrice.Text = "0";
            txtBasicFreight.Text = "0";
            txtOrderTotalAmount.Text = "0";
            txtCustomerSaleCount.Text = "0";
        }

        //订单审核
        private void btnCheck_Click(object sender, EventArgs e)
        {
            if (!m_ActionList.Contains((int)ActionEnum.OrderCheck))
            {
                MessageBox.Show(this, "该用户无订单审核权限！");
                return;
            }
            if (m_OrderInfo.audited)
            {
                MessageBox.Show(this, "该订单已审核，不能再次审核！");
                return;
            }
            if (m_OrderInfo.productPrice == 0)
            {
                MessageBox.Show(this, "该订单尚未确定价格，不能审核！");
                return;
            }
            long belongCorpId = long.Parse(ConfigurationManager.AppSettings["BelongCorpId"].ToString());
            decimal saleCount =  DataHelper.GetCusBalances(m_CurrentUser, m_Password, belongCorpId, m_OrderInfo.customerId, 1);
            //如果客户销售金额不足给出提示
            decimal orderTotalAmount = Convert.ToDecimal(txtOrderTotalAmount.Text.Trim());
            if (saleCount < orderTotalAmount)
            {
                if (MessageBox.Show("该客户可销售金额:" + saleCount.ToString("0.00") + "不足以支付当前订单,是否继续审核？",
                    "", MessageBoxButtons.YesNo) != DialogResult.Yes)
                    return;
            }
            try
            {
                bool isSuccess = DataHelper.AuditedSaleOrder(m_CurrentUser, m_Password, m_OrderInfo.mainId, true);
                if (!isSuccess)
                    return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "订单审核失败：" + ex.Message);
                return;
            }
            MessageBox.Show(this, "订单审核成功!");
            m_OrderInfo.audited = true;
            m_OrderInfo.executeStatus = (int)ExecuteStatusEnum.EXECUTE;
            //刷新订单列表
            if (RefreshEvent != null)
                RefreshEvent(this, e);
        }


        //确认配比
        private void btnAcceptFormula_Click(object sender, EventArgs e)
        {
            if (!m_ActionList.Contains((int)ActionEnum.Formula))
            {
                MessageBox.Show(this, "该用户无确认配比权限！");
                return;
            }
            //需审核过的订单才能确认配比
            if (!m_OrderInfo.audited)
            {
                MessageBox.Show("订单尚未审核，不能确认配比！");
                return;
            }
            DataRow currentRow = gdvBalance.GetFocusedDataRow();
            if (currentRow == null)
            {
                MessageBox.Show(this, "请先选择需要执行的实施配比!");
                return;
            }
            if (currentRow["executeStatus"].ToString() == "已执行")
            {
                MessageBox.Show(this, "该实施配比已执行，请重新选择!");
                return;

            }
            if (m_OrderInfo.materialId == long.Parse(ConfigurationManager.AppSettings["DefaultMaterialId"].ToString()))
            {
                MessageBox.Show("配方代码未默认配方，不能确认配比，请刷新订单！");
                return;
            }
            DataTable dt = m_SubDT.Clone();
            var query = from temp in m_SubDT.AsEnumerable()
                        where long.Parse(temp["mainId"].ToString()) == long.Parse(currentRow["id"].ToString())
                        select temp;
            foreach (DataRow dr in query)
                dt.Rows.Add(dr["mainId"], dr["id"], dr["code"], dr["name"], dr["sstd"], dr["quantity"], dr["controlStoreName"]);

            //将实施配方的助记码填入订单
            m_OrderInfo.otherCode = currentRow["otherCode"].ToString().Trim();
            //需往机楼程序中插入
            if (!InsertMachineProgram(m_OrderInfo, dt, false))
            {
                return;
            }
            //第一次执行实施配比的时候将订单执行状态改为已执行
            try
            {
                //判断是否第一次确认配比
                bool isFirst = true;
                for (int i = 0; i < gdvBalance.RowCount; i++)
                {
                    DataRow dr = gdvBalance.GetDataRow(i);
                    if (dr["executeStatus"].ToString() == "已执行")
                    {
                        isFirst = false;
                        break;
                    }
                }
                if (isFirst)
                {
                    if (!DataHelper.UpdateExecuteStatus(m_CurrentUser, m_Password,
                        m_OrderInfo.id, (int)ExecuteStatusEnum.EXECUTE))
                        return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "更新订单执行状态失败:" + ex.Message);
                return;
            }
            //插入成功后需将改记录保存为已执行，并且赋值执行时间
            try
            {
                long id = long.Parse(currentRow["id"].ToString());
                if (!DataHelper.UpdateFormulaExecuteStatus(m_CurrentUser, m_Password, id, true))
                    return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "更新实施配比状态失败:" + ex.Message);
                return;
            }
            MessageBox.Show(this, "确认实施配比成功！");
            BackgroundWorker backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += backgroundWorker_DoWork;
            backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
            backgroundWorker.RunWorkerAsync(m_OrderInfo.id);
        }


        //更新配比
        private void btnUpdateFormula_Click(object sender, EventArgs e)
        {
            if (!m_ActionList.Contains((int)ActionEnum.Formula))
            {
                MessageBox.Show(this, "该用户无更新配比权限！");
                return;
            }
            DataRow currentRow = gdvBalance.GetFocusedDataRow();
            if (currentRow == null)
            {
                MessageBox.Show(this, "请先选择需要更新的实施配比!");
                return;
            }
            if (currentRow["executeStatus"].ToString() != "已执行")
            {
                MessageBox.Show(this, "更新配比需先确认,请重新选择!");
                return;
            }
            DataTable dt = m_SubDT.Clone();
            var query = from temp in m_SubDT.AsEnumerable()
                        where long.Parse(temp["mainId"].ToString()) == long.Parse(currentRow["id"].ToString())
                        select temp;
            foreach (DataRow dr in query)
                dt.Rows.Add(dr["mainId"], dr["id"], dr["code"], dr["name"], dr["sstd"], dr["quantity"]);
            //需往机楼程序中插入
            if (!InsertMachineProgram(m_OrderInfo, dt, true))
            {
                return;
            }
            //插入成功后需将改记录保存为已执行，并且赋值执行时间
            try
            {
                long id = long.Parse(currentRow["id"].ToString());
                if (!DataHelper.UpdateFormulaExecuteStatus(m_CurrentUser, m_Password, id, true))
                    return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "更新实施配比状态失败:" + ex.Message);
                return;
            }
            MessageBox.Show(this, "更新实施配比成功！");
            BackgroundWorker backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += backgroundWorker_DoWork;
            backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
            backgroundWorker.RunWorkerAsync(m_OrderInfo.id);
        }


        public delegate void myReturnEventHandler(object sender, EventArgs e);
        public event myReturnEventHandler myReturnEvent;
        //返回
        private void btnReturn_Click(object sender, EventArgs e)
        {
            if (myReturnEvent != null)
                myReturnEvent(null, null);
        }

        public delegate void RefreshEventHandler(object sender, EventArgs e);
        public event RefreshEventHandler RefreshEvent;
        #endregion

        #region 下拉框变化事件
        //工程名称变化随之实际距离变化
        private void mruEditProjectName_SelectedIndexChanged(object sender, EventArgs e)
        {
            string projectName = mruEditProjectName.Text.Trim();
            if (string.IsNullOrEmpty(projectName))
                return;
            //根据工程名称带出实际距离
            List<ProjectInfo> projecInfoList = DataHelper.GetProjectInfo(m_CurrentUser, m_Password, projectName);
            if (projecInfoList == null || projecInfoList.Count == 0)
            {
                this.spinEditActualDistance.Value = 0;
                return;
            }
            if (projecInfoList[0].range == "")
                this.spinEditActualDistance.Value = 0;
            else
                 this.spinEditActualDistance.Value = Convert.ToDecimal(projecInfoList[0].range);
            if (projecInfoList[0].zoneInfo == null || projecInfoList[0].zoneInfo.id == -1)
                mruEditZone.SelectedIndex = -1;
            else
                mruEditZone.SelectedItem = CommonHelper.FindDataInfoByKey(mruEditZone,
                    projecInfoList[0].zoneInfo.id);
        }

        //客户变化事件
        private void mruEditCustomer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (mruEditCustomer.SelectedItem == null || mruEditCustomer.SelectedItem == "")
            {
                m_SelectedCustomerId = -1;
                this.txtCustomerSaleCount.Text = "0";
            }
            else
            {
                if (mruEditCustomer.SelectedItem as DataInfo != null)
                {
                    m_SelectedCustomerId = ((DataInfo)mruEditCustomer.SelectedItem).Id;
                    long belongCorpId = long.Parse(ConfigurationManager.AppSettings["BelongCorpId"].ToString());

                    //获取客户可销售金额
                    try
                    {
                        decimal saleCount = DataHelper.GetCusBalances(m_CurrentUser, m_Password, belongCorpId, m_SelectedCustomerId, 1);
                        this.txtCustomerSaleCount.Text = saleCount.ToString("0.00");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message);
                        return;
                    }
                    //若是默认的配方代码，无需去产品价格
                    if (m_SelectedmaterialId != long.Parse(ConfigurationManager.AppSettings["DefaultMaterialId"].ToString()))
                    {
                        //获取产品价格
                        try
                        {
                            decimal orderPrice = DataHelper.GetOrderPrice(m_CurrentUser, m_Password, belongCorpId, m_SelectedCustomerId,
                                m_SelectedmaterialId, DateTime.Now);
                            if (orderPrice == -1)
                                return;
                            this.txtProductPrice.Text = orderPrice.ToString();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(this, ex.Message);
                            return;
                        }
                    }
                }
                else
                {
                    m_SelectedCustomerId = -1;
                    this.txtCustomerSaleCount.Text = "0";
                }
            }
        }

        //生产线变化事件
        private void mruEditWorking_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (mruEditWorking.SelectedItem == null || mruEditWorking.SelectedItem == "")
                m_SelectedWorkingId = -1;
            else
            {
                if (mruEditWorking.SelectedItem as DataInfo != null)
                {
                    m_SelectedWorkingId = ((DataInfo)mruEditWorking.SelectedItem).Id;
                    if (m_OrderInfo != null)
                    {
                        m_OrderInfo.workingId = m_SelectedWorkingId;
                        m_OrderInfo.workingCenterName = this.mruEditWorking.Text.Trim();
                    }
                }
                else
                    m_SelectedWorkingId = -1;
            }
        }

        //区域变化
        private void mruEditZone_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtZonePrice.Text = "0";
            txtBasicPrice.Text = "0";
            txtOverPrice.Text = "0";
            txtBasicPath.Text = "0";
            if (mruEditZone.SelectedItem != null && mruEditZone.SelectedItem != "")
            {
                if (mruEditZone.SelectedItem as DataInfo != null)
                {
                    long id = ((DataInfo)mruEditZone.SelectedItem).Id;
                    //根据ID获取区域信息
                    var query = from temp in m_ZoneInfoList
                                where temp.id == id
                                select temp;
                    if(query.ToList().Count >= 0)
                    {
                        ZoneInfo zone = query.ToList<ZoneInfo>()[0];
                        txtBasicPrice.Text = zone.basicPrice.ToString();
                        txtOverPrice.Text = zone.overPrice.ToString();
                        txtBasicPath.Text = zone.basicDistance.ToString();
                        txtZonePrice.Text = zone.price.ToString();
                    }
                }
            }
        }
        #endregion

        #region 向机楼程序插入实施配比
        private bool m_IsNeedCover = false;
        private bool InsertMachineProgram(OrderInfo order, DataTable subDT, bool isUpdate)
        {
            //0只插入订单信息，1既插入订单信息也插入配方信息
            int way = int.Parse(ConfigurationManager.AppSettings["ExcuteFormulaWay"].ToString());
            int type = int.Parse(ConfigurationManager.AppSettings["MachineType"].ToString());
            if (way == 0)
                return true;
            if (way == 1 && !isUpdate)
            {
                if (!InsertOrderInfo(order, type))
                    return false;
            }
            else if (way == 2)
            {
                //判断实施配方是否已经存在，若存在，则提示是否要覆盖，确定后则覆盖
                if (type == 0 || type == 1)
                {
                    if (!isUpdate)
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.AppendFormat("select * from RecipeMain where RecipeCode = '{0}'", 
                            order.otherCode != "" ? order.otherCode : order.materialCode);
                        DataTable tempDT = SqlServerHelper.CreateInstance().DoSqlSelect(sb.ToString());
                        if (tempDT != null && tempDT.Rows.Count >= 1)
                        {
                            if (DialogResult.Yes != MessageBox.Show(this, "机楼系统中存在相同配方代码，是否覆盖？",
                                "", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                            {
                                return false;
                            }
                            m_IsNeedCover = true;
                        }
                    }
                }

                string sql = "select MaterialName,MaterialType from MaterialTypeList";
                DataTable dt = SqlServerHelper.CreateInstance().DoSqlSelect(sql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        string materialName = dr["MaterialName"].ToString();
                        string materialType = dr["MaterialType"].ToString();
                        if (!m_MaterialNameAndTypeDic.ContainsKey(materialName))
                            m_MaterialNameAndTypeDic.Add(materialName, materialType);
                        else
                            m_MaterialNameAndTypeDic[materialName] = materialType;
                    }
                }
                if (!isUpdate)
                {
                    //判断订单是否插入，若插入，则跳过
                    StringBuilder sb = new StringBuilder();
                    sb.AppendFormat("select * from JOBINFO where Jobno = '{0}'", order.orderCode);
                    DataTable orderDT = SqlServerHelper.CreateInstance().DoSqlSelect(sb.ToString());
                    if (orderDT == null || orderDT.Rows.Count == 0)
                    {
                        if (!InsertOrderInfo(order, type))
                            return false;
                    }
                }
                if (!InsertFormulaInfo(order, subDT, type, isUpdate))
                    return false;
            }
            return true;
        }
        
        //往机楼插入订单信息
        private bool InsertOrderInfo(OrderInfo order, int type)
        {
            // type 机楼程序类型，0：SQLServer如CB4500(现场使用)，1：SQLServer如CB4500(测试使用)
            bool flag = false;
            try
            {
                decimal numberEachCar = decimal.Parse(ConfigurationManager.AppSettings["NumberEachCar"].ToString());
                if (type == 0 || type == 1)
                {
                    //    State	, --  工作单状态 (0开工,1等待,2完工)
                    //      ModeTag  ,生产模式 (演示版插1，正式版插2)
                    StringBuilder sb = new StringBuilder();
                    sb.AppendFormat("insert into JOBINFO (Jobno, CustomerName, CustomerCode, SiteName, SiteAddress, Project, State, RecipeCode, Total, "
                        + "Slumpname, Volume,  Cgrade, Sitemileage, PlanDateTime, ProductLine, ModeTag, PumpTruck, DocketStyle, Remark1) values('{0}', '{1}','{2}','{3}','{4}','{5}',{6},'{7}',{8},"
                        + "'{9}',{10},'{11}',{12},'{13}','{14}',{15}, '{16}', '{17}', '{18}')", order.orderCode, order.customerName, order.customerCode, order.projectName, order.constructionAddr,
                        order.constructSite, 1, order.otherCode != ""? order.otherCode : order.materialCode, order.orderQuantity, order.materialSlump, numberEachCar, order.materialSstd, order.actualRange,
                        order.productDate.ToString("yyyy-MM-dd HH:mm:ss"), order.workingCenterName, type == 0 ? 2 : 1, order.transport, "", order.phone);

                    if (!SqlServerHelper.CreateInstance().DoSqlExecute(new string[] { sb.ToString() }))
                        flag = false;
                    flag = true;
                }
                else if (type == 2)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendFormat("insert into JOBINFO (JOBNO, CNAME, CCODE, SNAME, PROJECT1, RECIPE, TOTAL, "
                        + "SLUMPNAME, VOLUME,  CGRADE, SITEMILE, PRODLINE, PUMPTRUCK) values('{0}', '{1}','{2}','{3}','{4}','{5}',{6},'{7}',{8},"
                        + "'{9}',{10},'{11}','{12}')", order.orderCode.Substring(order.orderCode.Length -10), order.customerName, order.customerCode, order.projectName, order.constructSite, order.materialCode,
                        order.orderQuantity, order.slump, numberEachCar, order.strengthGrade, order.actualRange, order.workingCenterName, order.transport);

                    if (!ParadoxHelper.CreateInstance().DoSqlExecute("customer", new string[] { sb.ToString() }))
                        flag = false;
                    flag = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("插入订单信息异常：" + ex.Message);
                return false;
            }       
            return flag;
        }
 
        //往机楼插入配方信息信息
        private bool InsertFormulaInfo(OrderInfo order, DataTable subDT, int type, bool isUpdate)
        {
            bool flag = false;
            try
            { 
                if (type == 0 || type == 1)
                {
                    List<string> list = new List<string>();
                    StringBuilder sb = new StringBuilder();
                    if (m_IsNeedCover || isUpdate)
                    {
                        string recipeCode = order.otherCode != "" ? order.otherCode : order.materialCode;
                        sb.AppendFormat("delete from RecipeMain where RecipeCode = '{0}'", recipeCode);
                        list.Add(sb.ToString());
                        sb = new StringBuilder();
                        sb.AppendFormat("delete from RecipeList where RecipeCode = '{0}'", recipeCode);
                        list.Add(sb.ToString());
                        if (!SqlServerHelper.CreateInstance().DoSqlExecute(list.ToArray()))
                            return false;
                    }
                    list = new List<string>();
                    sb = new StringBuilder();
                    sb.AppendFormat("insert into RecipeMain (RecipeCode, Cgrade, SlumpName, ProductLine, RecipeType,LabRecipeCode)values('{0}','{1}','{2}', '{3}', '{4}', '{5}')",
                        order.otherCode != "" ? order.otherCode : order.materialCode, order.materialSstd, order.materialSlump,
                        order.workingCenterName, "A", "");
                    list.Add(sb.ToString());
                    int index = 1;
                    foreach (DataRow dr in subDT.Rows)
                    {
                        sb = new StringBuilder();
                       
                        string materialCode = dr["code"].ToString();
                        string materialName = dr["name"].ToString();
                        //仓位
                        string controlStoreName = dr["controlStoreName"].ToString();
                        //物料对照,不需要对照
                        //if (m_MaterialCrossDic.ContainsKey(materialCode))
                        //    materialName = m_MaterialCrossDic[materialCode];
                        //TODO 物料类型
                        string materialType = "";
                        if (m_MaterialNameAndTypeDic.ContainsKey(controlStoreName))
                            materialType = m_MaterialNameAndTypeDic[controlStoreName];
                        decimal quantity = decimal.Parse(dr["quantity"].ToString());
                        sb.AppendFormat("insert into RecipeList(RecipeCode, MaterialName, MaterialType, Mdesign, Macademic, ProductLine, RecipeType, Id, Range_From, Range_To, Moist, MAdjust, CreateDate, RockRate)"
                            + " values ('{0}', '{1}', '{2}', {3}, {4}, '{5}', '{6}', {7},{8}, {9}, {10}, {11},'{12}', {13})",
                              order.otherCode != "" ? order.otherCode : order.materialCode, controlStoreName, materialType, 
                              quantity, quantity, order.workingCenterName, "A", index++, 0, 0, 0, 0, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), 0);
                        list.Add(sb.ToString());
                    }
                    if (!SqlServerHelper.CreateInstance().DoSqlExecute(list.ToArray()))
                        flag = false;
                    flag = true;
                }
                else if (type == 2)
                {
                    List<string> list = new List<string>();
                    StringBuilder sb = new StringBuilder();
                    sb.AppendFormat("insert into re_main (RECIPECODE, NAME, SLUMPNAME, PL, TYPE)values('{0}','{1}','{2}', '{3}', '{4}')",
                        order.materialCode, order.strengthGrade, order.slump, order.workingCenterName, "A");
                    list.Add(sb.ToString());
                    int index = 1;
                    foreach (DataRow dr in subDT.Rows)
                    {
                        sb = new StringBuilder();
                        string materialName = dr["name"].ToString();
                        //TODO 物料类型
                        string materialType = dr["name"].ToString();
                        decimal quantity = decimal.Parse(dr["quantity"].ToString());
                        sb.AppendFormat("insert into recipe(RECIPECODE, NAME, SETPOINT, PL, SEQUENCE, RANGE_FROM, RANGE_TO)"
                            + " values ('{0}', '{1}', {2}, '{3}', {4}, {5}, {6})",
                             order.materialCode, materialName, quantity, order.workingCenterName, index++, 0, 0);
                        list.Add(sb.ToString());
                    }
                    if (!ParadoxHelper.CreateInstance().DoSqlExecute("customer", list.ToArray()))
                        flag = false;
                    flag = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "插入配方信息异常：" + ex.Message);
                return false;
            }
            return flag;
        }
        #endregion

        //实际距离变化时，运费相应的变化
        private void spinEditActualDistance_EditValueChanged(object sender, EventArgs e)
        {
            ValueChange();
        }

        //数量变化时基本运费和混凝土货款相应变化
        private void spinEditNumber_EditValueChanged(object sender, EventArgs e)
        {
            ValueChange();
        }

        //区域变化时相关信息跟着变化
        private void mruEditZone_TextChanged(object sender, EventArgs e)
        {
            ValueChange();
        }

        private void txtZonePrice_TextChanged(object sender, EventArgs e)
        {
            ValueChange();
        }

        //值变化时关联的其他值变化
        private void ValueChange()
        {
            //订单数量
            decimal number = Convert.ToDecimal(this.spinEditNumber.EditValue);
            //区域调价
            decimal zonePrice = Convert.ToDecimal(this.txtZonePrice.Text.Trim());
            //产品价格
            decimal productPrice = Convert.ToDecimal(this.txtProductPrice.Text.Trim());
            //单价
            decimal unitPrice = zonePrice + productPrice;
            if (unitPrice < 0)
                unitPrice = 0;
            this.txtUnitPrice.Text = unitPrice.ToString();
            //基本计价路程
            decimal basicPath = Convert.ToDecimal(this.txtBasicPath.Text.Trim());
            //基本运价
            decimal basicPrice = Convert.ToDecimal(this.txtBasicPrice.Text.Trim());
            //超公里运价
            decimal overPrice = Convert.ToDecimal(this.txtOverPrice.Text.Trim());
            //实际距离
            decimal actualDistance = Convert.ToDecimal(this.spinEditActualDistance.EditValue);

            //混泥土货款 = 数量* 单价
            this.txtConcreteLoan.Text = (number * unitPrice).ToString();
            //超公里路程
            decimal overDistance = actualDistance - basicPath < 0 ? 0 : actualDistance - basicPath;
            //超公里路程= 实际距离-基本计价路程
            this.txtOverDistance.Text = overDistance.ToString();
            //每方实际运价= 基本运价+ 超公里运价* 超公里路程
            this.txtEachUnitPrice.Text = (basicPrice + overPrice * overDistance).ToString();
            //基本运费 = 每方实际运价* 数量
            this.txtBasicFreight.Text = ((basicPrice + overPrice * overDistance) * number).ToString();
            //订单合计金额 = 基本运费+ 混凝土货款
            this.txtOrderTotalAmount.Text = (((basicPrice + overPrice * overDistance) * number)
                + (number * unitPrice)).ToString();
        }

        private void gdvBalance_MasterRowExpanded(object sender, DevExpress.XtraGrid.Views.Grid.CustomMasterRowEventArgs e)
        {
            //将明细的数据赋值gridviewdetail中
            DevExpress.XtraGrid.Views.Grid.GridView gridviewdetail = 
                gdvBalance.GetDetailView(e.RowHandle, e.RelationIndex) as DevExpress.XtraGrid.Views.Grid.GridView;
            gridviewdetail.Columns[0].Visible = false;
            gridviewdetail.Columns[1].Visible = false;
        }

        private void spinEditNumber_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
             if (e.NewValue != null && e.NewValue.ToString().StartsWith("-"))
            {
                e.Cancel = true;
            }
        }

        private void mruEditCustomer_TextChanged(object sender, EventArgs e)
        {
            //long belongCorpId = long.Parse(ConfigurationManager.AppSettings["BelongCorpId"].ToString());
            ////获取客户可销售金额
            //try
            //{
            //    decimal saleCount = DataHelper.GetCusBalances(m_CurrentUser, m_Password, belongCorpId, m_SelectedCustomerId, 0);
            //    this.txtCustomerSaleCount.Text = saleCount.ToString("0.00");
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(this, ex.Message);
            //    return;
            //}
        }

        private void gdvBalance_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void mruEditCustomer_QueryPopUp(object sender, CancelEventArgs e)
        {
            //初始化客户
            InitMruEditCustomer(m_BaseDataInfo.CustomerInfoList);
        }
    }
}
